package com.haizhi.crm.biz.task.message.handler;

import com.haizhi.crm.biz.model.MessageUserVo;
import com.haizhi.crm.biz.task.message.model.ContextDto;
import com.haizhi.crm.sys.message.dao.MessageCategoryDao;
import com.haizhi.crm.sys.message.model.MessageCategoryDo;
import com.haizhi.crm.sys.message.service.MessageSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangshan on 2018/5/29.
 */
@Component
public class MessageSettingHandler extends AbstractHandler<ContextDto> {


    @Autowired
    private MessageSettingService messageSettingService;

    @Autowired
    private MessageCategoryDao messageCategoryDao;

    @Override
    protected MsgResponse process(ContextDto data) {
        String msgType = data.getEventType();
        MessageCategoryDo messageCategoryDo = messageCategoryDao.findBySourceName(msgType);
        if (messageCategoryDo == null) {
            return MsgResponse.error("sourceName not match : " + msgType);
        }
        data.setMsgCategoryId(messageCategoryDo.getId());
        Map<Long, MessageUserVo> result = new HashMap<Long, MessageUserVo>();
        for (MessageUserVo messageUserVo : data.getMessageUserVoMap().values()) {
            Long userId = messageUserVo.getUserId();
            boolean flag = messageSettingService.hasSetting(userId, msgType);
            if (flag) {
                result.put(userId, messageUserVo);
            }
        }
        data.setMessageUserVoMap(result);
        return MsgResponse.success();
    }
}
